﻿using System;
using System.Diagnostics;
using System.Windows;

namespace Example.Silverlight
{
    public partial class App
    {

        public App()
        {
            Startup += ApplicationStartup;
            Exit += ApplicationExit;
            UnhandledException += ApplicationUnhandledException;

            InitializeComponent();
        }

        private void ApplicationStartup(object sender, StartupEventArgs e)
        {
            RootVisual = new MainPage();
        }

        private static void ApplicationExit(object sender, EventArgs e)
        {

        }

        private static void ApplicationUnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (Debugger.IsAttached) return;
            e.Handled = true;
            Deployment.Current.Dispatcher.BeginInvoke(() => ReportErrorToDom(e));
        }

        private static void ReportErrorToDom(ApplicationUnhandledExceptionEventArgs e)
        {
            var errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
            errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");

            System.Windows.Browser.HtmlPage.Window.Eval(
                "throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
        }
    }
}
